﻿#region "Copyright (C) Lenny Granovsky. 2005-2013"
//This program is free software distribute under the terms of the GNU General Public License as published by
//the Free Software Foundation. Please read AssemblyInfo.cs file for more information.
#endregion

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.Enhancements.Rest;

namespace Web.Enhancements.Rest.WebControls
{
    /// <summary>
    /// Manages REST-services script files, error handler override and parameters, 
    /// and javascript client proxy classes generated for REST-service enabled .NET classes.
    /// </summary>
    [DefaultProperty("Classes")]
    [ToolboxData("<{0}:RestClientManager runat=server></{0}:RestClientManager>")]
    [ParseChildren(true), PersistChildren(false)]
    public class RestClientManager : CompositeControl
    {
        private ClassReferenceCollection classes;
        private ScriptReferenceCollection scripts;
        private ErrorHandling errorHandling;

        /// <summary>
        /// Gets or sets the collection of REST-service enabled classes used to generate javascript client proxy classes. 
        /// </summary>
        [MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty)]
        public ClassReferenceCollection Classes
        {
            get
            {
                return this.classes;
            }
            set
            {
                this.classes = value;
            }
        }

        /// <summary>
        /// Gets a ScriptReferenceCollection object that contains the ScriptReference objects, each of which represents a script file rendered to the client.
        /// </summary>
        [MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty)]
        public ScriptReferenceCollection Scripts
        {
            get
            {
                return this.scripts;
            }
            set
            {
                this.scripts = value;
            }
        }

        /// <summary>
        /// Gets or sets the custom settings for client-side REST-service error handling.
        /// </summary>
        [MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty)]
        public ErrorHandling ErrorHandling
        {
            get
            {
                return this.errorHandling;
            }
            set
            {
                this.errorHandling = value;
            }
        }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public RestClientManager()
            : base()
        {
            this.classes = new ClassReferenceCollection();
            this.scripts = new ScriptReferenceCollection();
            this.errorHandling = new ErrorHandling();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            foreach (ClassReference iclass in this.classes)
            {
                Type type = Activator.CreateInstance(iclass.Assembly, iclass.FullClassName).GetType();
                WebRestClient.RegisterJSClient(type);
            }
            int ii = 0;
            foreach (ScriptReference script in this.scripts)
            {
                ii++;
                if (script.Name.Length == 0)
                    script.Name = string.Concat(script.ToString(), (ii++).ToString());
                if (!this.Page.ClientScript.IsClientScriptIncludeRegistered(script.Name))
                    this.Page.ClientScript.RegisterClientScriptInclude(this.Page.GetType(), script.Name, script.Path);
            }
            if (!string.IsNullOrWhiteSpace(this.errorHandling.ErrorMessageStartsWith))
            {
                string jscript = string.Format(@"if (typeof(webRestExplorer)!=""undefined""){{
    webRestExplorer.errorMessageStartsWith = ""{0}"";{1}
}}", this.errorHandling.ErrorMessageStartsWith, this.errorHandling.ClientDelegateName.Length == 0 ? "" : string.Format(" if (typeof({0})!=\"undefined\"){{ webRestExplorer.errorHandler = {0}; }}", this.errorHandling.ClientDelegateName));
                if (!this.Page.ClientScript.IsStartupScriptRegistered("RestErrorHandlerSettings"))
                    this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "RestErrorHandlerSettings", jscript, true);
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
        }
    }
}
